package com.sparrow.config;

import com.sparrow.manage.user.UserService;
import com.sparrow.manage.auth.shiro.ShiroRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 后台管理系统认证配置
 */
@Configuration
public class ShiroConfigurer {

    // 验证服务
    @Bean
    public AuthorizingRealm shiroRealm(UserService userService) {
        ShiroRealm shiroRealm = ShiroRealm.instance();
        shiroRealm.setUserService(userService);
        return shiroRealm;
    }


    // 安全管理器
    @Bean
    public SecurityManager securityManager(AuthorizingRealm shiroRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(shiroRealm);
        return manager;
    }


    // 安全拦截配置
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 这里必须是LinkedHashMap
        Map<String,String> map = new LinkedHashMap<String, String>();

        // 不需要认证
        map.put("/manage/css/**", "anon");
        map.put("/manage/data/**", "anon");
        map.put("/manage/font/**", "anon");
        map.put("/manage/imgs/**", "anon");
        map.put("/manage/js/**", "anon");
        map.put("/manage/lib/**", "anon");

        // 对所有用户认证
        // 注意这里的配置顺序是有要求的, 必须先配置/manage下放行的目录, 再配置/manage/**拦截
        map.put("/manage/**", "authc");
        map.put("/preview/**", "authc");

        //登录
        shiroFilterFactoryBean.setLoginUrl("/manage/login");
        //首页
        shiroFilterFactoryBean.setSuccessUrl("/manage/index");
        //错误页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    // 启用权限拦截注解
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}
